#!/bin/sh -e

while true; do
    uuid=$(rkt list --no-legend | awk '{if ($4 == "running" && $2 == "chrony") print $1}')
    if [ "$uuid" != "" ]; then
        break
    fi
done

while true; do
    if rkt enter --app=chrony $uuid /bin/true 2>/dev/null; then break; fi
    echo "chrony-wait: retrying..."
    sleep 1
done

for i in $(seq 600); do
  rkt enter --app=chrony $uuid chronyc waitsync 1 0.1 0.0 1 && exit 0
  sleep 1
done

echo >&2 "Timed-out to synchronize NTP to upstream servers"
exit 1
